package com.captain.lc.滑动窗口;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;

/**
 * Des:
 *
 * @author XL
 * @Date 2021/10/9 17:13
 */
public class LengthOfLongestSubstring03 {

    public int lengthOfLongestSubstring(String s) {
        if (Objects.isNull(s)) return 0;
        //解题思路  abcabcbb
        int slow = 0;
        int max = 0;
        int len = s.length();
        int tempMax = 1;
        HashSet<Character> map = new HashSet<>();
        for (int i = slow; i < len; i++) {
            char cur = s.charAt(i);
            map.add(cur);
            for (int k = i + 1; k < len; k++) {
                char next = s.charAt(k);
                if (map.contains(next)) {
                    map.clear();
                    break;
                }
                tempMax++;
                map.add(next);
            }
            max = Math.max(max, tempMax);
            tempMax = 1;
        }
        return max;
    }

    public int lengthOfLongestSubstring2(String s) {
        //解题思路 : aaccbdfgab 滑动窗口  max = i - left
        int left = 0;
        int max = 0;
        int len = s.length();
        Map<Character, Integer> map = new HashMap<>(s.length());
        for (int i = 0; i < len; i++) {
            char cur = s.charAt(i);
            if (map.containsKey(cur)) {
                //移动左边的值
                left = Math.max(left, map.get(cur) + 1);
            }
            map.put(cur, i);
            max = Math.max(max, (i - left) + 1);
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(new LengthOfLongestSubstring03().lengthOfLongestSubstring2("aaccbdfgab"));

    }

}
